<?php
require_once(dirname(__FILE__).'/Abstract.php');

/**
 * MyAccount
 * 
 * Allows user to manage his an account, update his profile
 * 
 * @package Seowebd : Medic - Online
 * @author Seowebd
 * @copyright 2014
 * @version $Id$
 * @access public
 */
class MyAccount extends AbstractUserController 
{
	public function indexAction()
	{
		$this->profileAction();		
	}
	
	public function updateAction()
	{
            $d = array();
            $record = array();

            if ($this->session->userdata('id_user')){
            $this->load->model('ORM/User/UserEntityORM');
            $this->load->model('ORM/User/UserPatientORM');
            $this->load->model('ORM/User/UserDoctorORM');
            $idRolePatient = $this->getConfig('idRolePatient');
            $idRoleDoctor  = $this->getConfig('idRoleDoctor');
            $idRoleAdmin   = $this->getConfig('idRoleAdmin');
    		//$user = $this->UserEntityORM->getByIdUser(/*$this->session->userdata('id_user')*/1);
            if ($this->session->userdata('id_role')){
                switch ($this->session->userdata('id_role')) {
                    case $idRolePatient:
                        $d['patient'] = $this->UserPatientORM->getByIdUser($this->session->userdata('id_user'));
                        break;
                    case $idRoleDoctor:
                        $d['doctor'] = $this->UserDoctorORM->getByIdUser($this->session->userdata('id_user'));
                        break;
                    default:
                        # code...
                        break;
                }
            }

            if (empty($d['patient']) && empty($d['doctor'])){
                $d['title'] = $this->l('Complete your account.');
                $record1 = array(
                    'id_user' => $this->session->userdata('id_user'),
                    // Automatic fill
                    'cmu'    => 0,
                    'date_add'       => @date('Y-m-d H:i:s'),
                    'date_upd'       => @date('Y-m-d H:i:s'),
                );
            } elseif (isset($d['patient']) && (int)$d['patient']->id_patient != NULL) {
                $d['title'] = $this->l('Update your account.');
                $record1 = array(
                    'id_patient' => $d['patient']->id_patient,
                    // Automatic fill
                    'date_upd'       => @date('Y-m-d H:i:s'),
                );
            } elseif (isset($d['doctor']) && (int)$d['doctor']->id_doctor) {
                $d['title'] = $this->l('Update your account.');
                $record1 = array(
                    'id_doctor' => $d['doctor']->id_doctor,
                    // Automatic fill
                    'date_upd'       => @date('Y-m-d H:i:s'),
                );
            }

    		// On submit
        	if ($this->input->post('btn_submit') !== false){
                // Initialized the form validation
                $config = array(                   
                   array(
                         'field'   => 'phone', 
                         'label'   => $this->l('Phone'), 
                         'rules'   => 'trim|required|xss_clean'
                      ),
                   array(
                         'field'   => 'profession', 
                         'label'   => $this->l('Profession'), 
                         'rules'   => 'trim|xss_clean'
                      ),                   
                   array(
                         'field'   => 'address', 
                         'label'   => $this->l('Address'), 
                         'rules'   => 'trim|xss_clean'
                      ),
                );
                if ($this->session->userdata('id_role')){
                  switch ($this->session->userdata('id_role')) {
                    case $idRolePatient:
                      $patient = array( 
                           array(
                                 'field'   => 'birthday', 
                                 'label'   => $this->l('Birthday'), 
                                 'rules'   => 'trim|required|xss_clean'
                              ),
                           array(
                                 'field'   => 'pobox', 
                                 'label'   => $this->l('P.O.Box'), 
                                 'rules'   => 'trim|xss_clean'
                              ),
                           array(
                                 'field'   => 'town', 
                                 'label'   => $this->l('Town'), 
                                 'rules'   => 'trim|required|xss_clean'
                              ),
                           array(
                                 'field'   => 'nb_serur_social', 
                                 'label'   => $this->l('Social security number'), 
                                 'rules'   => 'trim|xss_clean'
                              ),
                        );
                      $config = array_merge($config, $patient);
                      break;
                    case $idRoleDoctor:
                      $doctor = array( 
                         array(
                               'field'   => 'medical_id', 
                               'label'   => $this->l('Medical Id'), 
                               'rules'   => 'trim|required|xss_clean'
                            ),
                      );
                      $config = array_merge($config, $doctor);
                      break;
                    default:
                      # code...
                      break;
                  }
                }
                $this->form_validation->set_rules($config);
    			
                if ($this->form_validation->run() == FALSE ){
                    $this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
                } else {
                	// Initialize the new record
                  if ($this->session->userdata('id_role')){
                  switch ($this->session->userdata('id_role')) {
                    case $idRolePatient:
                          $record2 = array(
                            'birthday'        => $this->input->post('birthday'),
                            'phone'       => $this->input->post('phone'),
                            'profession'    => $this->input->post('profession'),
                            'pobox'       => $this->input->post('pobox'),
                            'town'          => $this->input->post('town'),
                            'nb_secur_social'   => $this->input->post('nb_secur_social'),
                            'address'       => $this->input->post('address'),
                                      
                                      // Automatic fill
                            'cmu'    => 0,                             // The cmu default value
                          );
                  
                        // Create the new account
                          if ($this->UserPatientORM->save(array_merge($record1,$record2))) {
                            // Redirect to the account page
                              redirect('User/MyAccount/index');
                              die();
                          }
                      break;
                      case $idRoleDoctor:
                        $record2 = array(
                            'medical_id'        => $this->input->post('medical_id'),
                            'phone'       => $this->input->post('phone'),
                            'profession'    => $this->input->post('profession'),
                            'description'       => $this->input->post('description'),
                            'address'       => $this->input->post('address'),
                             
                          );
                  
                        // Create the new account
                          if ($this->UserDoctorORM->save(array_merge($record1,$record2))) {
                            // Redirect to the account page
                              redirect('User/MyAccount/index');
                              die();
                          }
                        break;
                  }
                    
    			       }
            }	} // Ens if posted datas		
		} //End if session userdata id_user
                    else {
                    // Redirect to the sign in form
                    redirect('User/AccountService/signIn');
                    die();
		}
                	
		$d['title_for_layout'] = $this->l('Manage your profile');
		$d['title'] = $this->l('Manage your profile');
    $d['menu'] = 'myaccount';
    $d['page_name'] = 'update';
		
		$this->load->view('Templates/Layouts/authLayout/header', $d);
    $this->load->view('User/MyAccount/Update', $d);
    $this->load->view('Templates/Layouts/authLayout/footer', $d);
	}


	public function profileAction()
	{
		$d = array();
		$d['title'] = $this->l('My Account');
		if ($this->session->userdata('id_user')){
			$this->load->model('ORM/User/UserEntityORM');
			$d['user'] = $this->UserEntityORM->getByIdUser($this->session->userdata('id_user'));
			
      $idRolePatient = $this->getConfig('idRolePatient');
      $idRoleDoctor  = $this->getConfig('idRoleDoctor');
      $idRoleAdmin   = $this->getConfig('idRoleAdmin');
      
      switch ($this->session->userdata('id_role')) {
				case $idRolePatient :
					$layout = 'Patient';
					$this->load->model('ORM/User/UserPatientORM');
					$d['patient'] = $this->UserPatientORM->getByIdUser($this->session->userdata('id_user'));
					break;
				case $idRoleDoctor :
					$layout = 'Doctor';
					$this->load->model('ORM/User/UserDoctorORM');
					$d['doctor'] = $this->UserDoctorORM->getByIdUser($this->session->userdata('id_user'));
					break;
				case $idRoleAdmin :
					$layout = 'Admin';
					break;
				default:
					$layout = 'Default';
					$this->load->model('ORM/User/UserPatientORM');
					$d['patient'] = $this->UserPatientORM->getByIdUser($this->session->userdata('id_user'));
					break;
			}
						
			$d['title_for_layout'] = $this->l('Manage your account.');
	        $d['menu'] = 'myaccount';
	        $d['page_name'] = 'profile';
			
	        
	        $this->load->view('Templates/Layouts/'.$layout.'/header', $d);
	        $this->load->view('User/MyAccount/Profile', $d);
	        $this->load->view('Templates/Layouts/'.$layout.'/footer', $d);
		} else {
			// Redirect to the sign in form
			redirect('User/AccountService/signIn');
            die();
		}
	}

	public function confirmationAction()
    {
		$d = array();
		$record = array();
        $this->load->model('ORM/User/UserEntityORM');
        
        if ($this->input->get_post('username') && $this->input->get_post('token')) {
            // Check if the account exist with the token
            $user = $this->UserEntityORM->getByUsernameAndToken($this->input->get_post('username'), $this->input->get_post('token'));
            if (!empty($user->id_user)) {
                if ($user->activated == 0) {
                    // Activation authorized
                    $record = array(
                        'id_user'       => $user->id_user, 
                        'activated'     => 1,
                        'last_activity' => @date('Y-m-d H:i:s') 
                        );
                    if ($this->UserEntityORM->save($record)) {
                        $this->session->set_flashdata('successMessage', $this->l('Your account was successfully confirmed. Contact a doctor on Medic Center for activating your account.'));
        				
                        // Send an alert to doctor
                        
                        // Go to sign in form
                        redirect('User/AccountService/signIn');
                        die();
                    } else {
                        $this->session->set_flashdata('errorMessage', $this->l('Confirmation of your account failed. Try again later or contact the support.'));
                    }
                } elseif ($user->activated == 1) {
                    $this->session->set_flashdata('successMessage', $this->l('Your account is already confirmed. Contact a doctor on Medic Center for activating your account.'));
    				redirect('User/AccountService/signIn');
                    die();
                } elseif ($user->activated == 2) {
                    $this->session->set_flashdata('successMessage', $this->l('Your account is already activated. You can sign in with you username and password.'));
    				redirect('User/AccountService/signIn');
                    die();
                }
            } else {
                // The account was not found
                $this->session->set_flashdata('errorMessage', $this->l('Confirmation of your account failed. Invalid token.'));
            }
            
        } elseif ($this->input->get_post('username')) {
            $user = $this->UserEntityORM->getByUsername($this->input->get_post('username'));
            if (!empty($user->id_user)) {
                $this->session->set_flashdata('errorMessage', $this->l('Confirmation of your account failed. Invalid token.'));
            } else {
                $this->session->set_flashdata('errorMessage', $this->l('Confirmation of your account failed. Invalid account.'));
            }
        } else {
            $this->session->set_flashdata('errorMessage', $this->l('Require the account and its token.'));
        }
        
        redirect('User/AccountService/signIn');
        die();
	}
    
}

